package com.eric.windows;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class ThreadlocalTestActivity extends Activity  {
    /**普通数据*/
    private int num = 0;
    /** 经过ThreadLocal处理的数据*/
    private ThreadLocal<Integer> threadLocalNum = new ThreadLocal<Integer>(){
        @Override
        protected Integer initialValue() {
            //初始值为0
            return 0;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_threadlocal_test);

        new Thread(new Runnable() {
            @Override
            public void run() {
                num += 1;
                threadLocalNum.set(threadLocalNum.get() + 1);
                Log.e("线程1===num=====》","" + num);// 线程1===num=====》: 1
                Log.e("线程1====threadLocal==》","" + threadLocalNum.get());// 线程1====threadLocal==》: 1
            }
        }).start();


        new Thread(new Runnable() {
            @Override
            public void run() {
                ThreadlocalTestActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        num += 1;
                        threadLocalNum.set(threadLocalNum.get() + 1);
                        Log.e("线程2========》","" + num);// 线程2========》: 2
                        Log.e("线程2====threadLocal==》","" + threadLocalNum.get());//线程2====threadLocal==》: 1
                    }
                });
            }
        }).start();

    }



    public class SimpleThreadLocal{
        private Map valueMap = Collections.synchronizedMap(new HashMap());
        /**
         * 设置副本的值
         * */
        public void set(Object newValue) {
            //①键为线程对象，值为本线程的变量副本
            valueMap.put(Thread.currentThread(), newValue);
        }
        /**
         *  获取副本的值
         * */
        public Object get() {
            Thread currentThread = Thread.currentThread();
            //②返回本线程对应的变量
            Object o = valueMap.get(currentThread);
            //③如果在Map中不存在，放到Map中保存起来。
            if (o == null && !valueMap.containsKey(currentThread)) {
                o = initialValue();
                valueMap.put(currentThread, o);
            }
            return o;
        }
        /**
         * 移除副本的值
         * */
        public void remove() {
            valueMap.remove(Thread.currentThread());
        }
        /**
         *
         * */
        public Object initialValue() {
            return null;
        }
    }


}
